layui.config({
	  base: '/resource/js/' //假设这是你存放拓展模块的根目录
	}).extend({}).define(['jquery','layer','form','rate'],function(exports){
	var layer = layui.layer;
	var f = layui.form;
	var $ = layui.$;
	var rate = layui.rate;
	var obj = {
			transform:function(req,data){
				var itemArr = [];
				if(typeof req.dimension == 'undefined' || typeof req.dimension.field == 'undefined') {
					var chartData = data;
					var item = {};
					__response_transform(itemArr,item,req.metric,chartData);
				}else {
					var dimensionField = req.dimension.field;
					var chartData = data[dimensionField];
					for(var key in chartData) {
						if(typeof req.metric == 'undefined' || req.metric.length == 0) {
							var item = {};
							item[dimensionField] = key;
							item['doc'] = chartData[key]['__doc'];
							itemArr.push(item);
						}else {
							for(var metric of req.metric) {
								var item = {};
								item[dimensionField] = key;
								__response_transform(itemArr,item,req.metric,chartData[key]);
								//itemArr.push(item);
							}
						}
					}
				}

				return itemArr;
			},
			clearJson:function(json){
				for (var entry in json) delete json[entry];
			},
			async_ajax:function(method,url,data,success){
				var xhr = new XMLHttpRequest();
				if(method == 'post') {
					var formData = new FormData();
					for(var d in data) {
						formData.append(d,data[d]);
					}
					xhr.open(method, url, false);
					xhr.send(formData);
					success($.parseJSON(xhr.responseText));
				}
				if(method == 'get') {
					var request_data = '';
					for(var d in data) {
						if(request_data == '') {
							request_data = d+'='+data[d];
						}else{
							request_data = request_data+'&'+d+'='+data[d];
						}
					}
					var new_url = url+'?'+request_data;
					xhr.open(method, new_url, false);
					xhr.send(null);
					console.log(xhr.responseText)
					success($.parseJSON(xhr.responseText));
				}
			},
			ajax:function(method,url,data,success){
				var xhr = new XMLHttpRequest();
				xhr.onreadystatechange = function() {
				      if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
				    	  if(xhr.responseURL.endsWith('/login')){
				    		  window.location = xhr.responseURL;
				    	  }else{
				    		  success($.parseJSON(xhr.responseText));
				    	  }
				      }
				    };
				if(method == 'post') {
					var formData = new FormData();
					for(var d in data) {
						formData.append(d,data[d]);
					}
					xhr.open(method, url, true);
					xhr.send(formData);
				}
				if(method == 'get') {
					var request_data = '';
					for(var d in data) {
						if(request_data == '') {
							request_data = d+'='+data[d];
						}else{
							request_data = request_data+'&'+d+'='+data[d];
						}
					}
					var new_url = url+'?'+request_data;
					xhr.open(method, new_url, true);
					xhr.send(null);
				}
			},
			fields:function(form){
				var fieldElem = $(form).find('input,select,textarea');
				var field={};
				 var nameIndex = {};
			    layui.each(fieldElem, function(_, item){
			        item.name = (item.name || '').replace(/^\s*|\s*&/, '');

			        if(!item.name) return;

			        //用于支持数组 name
			        if(/^.*\[\]$/.test(item.name)){
			          var key = item.name.match(/^(.*)\[\]$/g)[0];
			          nameIndex[key] = nameIndex[key] | 0;
			          item.name = item.name.replace(/^(.*)\[\]$/, '$1['+ (nameIndex[key]++) +']');
			        }

			        if(/^checkbox|radio$/.test(item.type) && !item.checked) return;
			        field[item.name] = item.value;
			      });
			    return field;
			},
			disableForm:function(form){
				var fieldElem = $(form).find('input,select,textarea');
				layui.each(fieldElem, function(_, item){
					$(item).attr("disabled","disabled");
					//$(item).attr("readonly","readonly");
				});
				$(form).find(".layui-btn").hide();
			},
			enableForm:function(form){
				var fieldElem = $(form).find('input,select,textarea');
				layui.each(fieldElem, function(_, item){
					$(item).removeAttr("disabled");
				});
				$(form).find(".layui-btn").show();
			},
			waitCondition:function(condition,time,func){
				var ttl = 0;
			    var cc;
			    var condition = true;
			    var c = function(){
					for(var c in condition) {
						if(typeof c == 'undefined') {
							condition = false;
							break;
						}
					}
					if(condition) {
						func();
						clearInterval(cc);
					}else{
						ttl++;
						if(ttl>time) {
							clearInterval(cc);
						}
					}
			    }
			    cc = setInterval(c,37);
			},
			fillForm:function(form,url,id,layero) {
				$.ajax({
				  type:'post',
		    	  url:url,
		    	  data:{id:id},
		    	  traditional: true,
		    	  success:function(data){
		    		  if(data.code==0) {
		    			  var inputElem = $(form).find('input[type!="radio"]');
		    			  var radioElem = $(form).find('input[type="radio"]');
			    		  var selectElem = $(form).find('select');
			    		  var textareaElem = $(form).find('textarea');
			    		  var rateElem = $(form).find('div[data-type="rate"]');
			    		  console.log(rateElem)
			    		  var filter = $(form).attr('lay-filter');
			    		  layui.each(inputElem, function(_, item){
								if(data.values.data[item.name]) {
									if(data.values.data[item.name+'Discard'] == 1) {
										$(item).val('(已废弃) '+data.values.data[item.name]);
									}else {
										$(item).val(data.values.data[item.name]);
									}
								}
							});
			    		  layui.each(radioElem,function(_,item){
			    			  if(data.values.data[item.name]) {
			    				  	if($(item).val() == data.values.data[item.name]) {
			    				  		$(item).attr("checked",true);
			    				  	}
								}
			    		  });
			    		  layui.each(textareaElem,function(_,item){
			    			  if(data.values.data[item.name]) {
									$(item).val(data.values.data[item.name]);
			    			  }
			    		  });
			    		  var iframeWin = window[layero.find('iframe')[0]['name']];
			    		  layui.each(rateElem,function(_,item){
			    			  console.log(item.id)
			    			  if(data.values.data[item.id]) {
									//$(item).val(data.values.data[item.name]);
			    				  iframeWin.layui.rate.render({
			    					  elem:'#'+item.id,
			    					  value:data.values.data[item.id],
			    					  choose:function(value){
			    						  $('input[name="'+item.id+'"]').val(value);
			    					  }
			    				  });
			    			  }
			    		  });

			    		  iframeWin.layui.form.render();
		    		  }else {
		    			  layer.msg(data.code+":"+data.msg);
		    		  }
		    		  window.layui.form.render()
		    		  console.log($(form).parents('window').context.layui)
		    	  },
		    	  error:function(resp){
		    		  layer.msg('error occur');
		    	  }
				});
			},
			bar:function(chart,option){
				data(chart,option);
				scale(chart,option);
				chart.interval().position(option.position);
				event(chart,option);
				return chart;
			},
			pie:function(chart,option){
				data(chart,option);
				scale(chart,option);
				coord(chart,option);
				chart_tooltip(chart,option);
				legend(chart,option);
				event(chart,option);
				var g = chart.interval().position(option.position).color(option.color);
				geom(g,option);
			},
			pic:function(chart,option){
				chartOption(chart,option);
				view(chart,option);
			}
	}
///////
	function __response_transform(itemArr,item,metrics,data) {
		for(var metric of metrics) {
			var chartData = data[metric.field];
			for(var key in chartData) {
				var sub = {};
				$.extend(sub,item);
				if(typeof metric.metric == 'undefined' || metric.metric.length == 0){
					if(metric.type == 'terms' || metric.type == 'count') {
						sub[metric.field] = key;
						sub['doc'] = chartData[key]['__doc'];
					}else {
						sub[metric.field+'.'+metric.type] = chartData[metric.type];
						sub['doc'] = chartData['__doc'];
					}
					itemArr.push(sub);
				}else {
					sub[metric.field] = key;
					__response_transform(itemArr,sub,metric.metric,chartData[key]);
				}
			}
		}

	}



	function chartOption(chart,option){
		legend(chart,option.legend);
		event(chart,option.event);
		ChartTooltip(chart,option.tooltip);
	}

	function legend(chart,legendDef) {
		if(typeof legendDef != 'undefined') {
			chart.legend(legendDef);
		}
	}
	function ChartTooltip(chart,tooltipDef) {
		if(typeof tooltipDef == 'object') {
			chart.tooltip(tooltipDef);
		}
	}

	function event(chart,eventDef) {
		if(typeof eventDef != 'undefined') {
			if(typeof eventDef.length == 'undefined') {
				chart.on(eventDef.type,eventDef.fn);
			}else{
				for(var e of eventDef) {
					var eventType = e.type;
					var fn = e.fn;
					chart.on(eventType,fn);
				}
			}
		}
	}
//View
//////////////
	function view(chart,option) {
		var data = option.data;
		var view = option.view;
		var ds = new DataSet();
		for(viewDef of view) {
			window._metric = viewDef.metric;
			var dv;
			var scaleDef = viewDef.scale;
			if(typeof viewDef.data == 'undefined') {
				if(typeof scaleDef == 'object') {
					dv = ds.createView().source(data,scaleDef);
				}else {
					dv = ds.createView().source(data);
				}
			}else{
				if(typeof viewDef.data == 'function') {
					if(typeof scaleDef == 'object') {
						dv = ds.createView().source(viewDef.data(viewDef),scaleDef);
					}else {
						dv = ds.createView().source(viewDef.data(viewDef));
					}
				}else{
					if(typeof scaleDef == 'object') {
						dv = ds.createView().source(viewDef.data,scaleDef);
					}else {
						dv = ds.createView().source(viewDef.data);
					}
				}
			}
			var transformDef = viewDef.transform;
			transform(dv,viewDef);

			var viewObj = chart.view();
			viewAxis(viewObj,viewDef);

			viewObj.source(dv);
			viewCoord(viewObj,viewDef);
			var geomDef = viewDef.geom;
			geom(viewObj,geomDef);
			window._metric = undefined;
		}
		//chart.source(dv);
	}

	function transform(dv,viewDef) {
		var transformDef = viewDef.transform;
		if(typeof transformDef != 'undefined') {
			for(var transformer of transformDef) {
				dv.transform(transformer);
			}
		}
	}

	function viewAxis(viewObj,viewDef) {
		if(typeof viewDef.axis != 'undefined') {
			var axisDef = viewDef.axis;
			if(typeof axisDef == 'string') {
				viewObj.axis(axisDef);
			}
			if(typeof axisDef == 'boolean') {
				viewObj.axis(axisDef);
			}
			if(typeof axisDef == 'object') {
				if(typeof axisDef.length == 'undefined') {
					viewObj.axis(axisDef.field,axisDef.config)
				}else{
					for(var axisC of axisDef) {
						if(typeof axisC == 'string') {
							viewObj.axis(axisC);
						}else{
							viewObj.axis(axisC.field,axisC.config)
						}
					}
				}
			}
		}
	}

	function viewCoord(viewObj,viewDef) {
		var coordDef = viewDef.coord;
		if(coordDef) {
			if(typeof coordDef == 'string') {
				viewObj.coord(coordDef);
			}
			if(typeof coordDef == 'object') {
				viewObj.coord(coordDef.type,coordDef.conf);
			}
		}
	}


//Geom
////////////
	function geom(viewObj,geomDef) {
		var geomObj;
		if(typeof geomDef != 'undefined') {
			var type = geomDef.type;
			if(type == 'interval') {
				geomObj = viewObj.interval();
			}
			if(type == 'intervalStack') {
				geomObj = viewObj.intervalStack();
			}
			if(type == 'line') {
				geomObj = viewObj.line();
			}
			if(type == 'position') {
				geomObj = viewObj.position();
			}
			geomPosition(geomObj,geomDef);
			geomColor(geomObj,geomDef);
			geomLabel(geomObj,geomDef);
			geomOpacity(geomObj,geomDef);
			geomAdjust(geomObj,geomDef);
			geomTooltip(geomObj,geomDef);
			geomStyle(geomObj,geomDef);
		}
	}

	function geomPosition(geomObj,geomDef) {
		if(typeof geomObj != 'undefined') {
			var position = geomDef.position;
			if(typeof position != 'undefined') {
				geomObj.position(position);
			}
		}
	}

	function geomLabel(geomObj,geomDef) {
		if(typeof geomObj != 'undefined') {
			var label = geomDef.label;
			if(typeof label != 'undefined') {
				geomObj.label(label);
			}
		}
	}

	function geomStyle(geomObj,geomDef) {
		if(typeof geomDef.style == 'object') {
			geomObj.style(geomDef.style);
		}
	}

	function geomColor(geomObj,geomDef) {
		if(typeof geomObj != 'undefined') {
			var color = geomDef.color;
			if(typeof color != 'undefined') {
				if(typeof color == 'string') {
					geomObj.color(color);
				}else{
					geomObj.color(color.field,color.colors);
				}
			}
		}
	}
	function geomOpacity(geomObj,geomDef) {
		if(typeof geomObj != 'undefined') {
			var opacity = geomDef.opacity;
			if(typeof opacity != 'undefined') {
				geomObj.opacity(opacity);
			}
		}
	}
	function geomAdjust(geomObj,geomDef) {
		if(typeof geomObj != 'undefined') {
			var adjust = geomDef.adjust;
			if(typeof adjust != 'undefined') {
				geomObj.adjust(adjust);
			}
		}
	}
	function geomTooltip(geomObj,geomDef) {
		if(typeof geomObj != 'undefined') {
			var tooltip = geomDef.tooltip;
			if(typeof tooltip != 'undefined') {
				if(typeof tooltip == 'string') {
					geomObj.tooltip(tooltip);
				}else{
					geomObj.tooltip(tooltip.field,tooltip.callback);
				}
			}
		}
	}

	exports('appJs',obj);
});


